package cn.enine.tbcharge.ui;


import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.adapter.CommonAdapter;
import cn.enine.tbcharge.adapter.ViewHolder;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.AppTj;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.MyApplication;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.enine.tbcharge.utils.AidlUtil;
import cn.enine.tbcharge.view.CustomDatePicker;
import cn.enine.tbcharge.view.XListView;

/**
 * 签约界面
 */

@SuppressLint("NewApi")
public class TjFragment extends Fragment {

    LinearLayout nocategoryLL, categoryLL;//内容布局
    ImageView nocategoryImg, categoryImg;//图表组
    TextView nocategoryTj, categoryTj, t3;//菜单文字组
    Context con;

    private int pageNum1 = 1;// 无关键字页数
    List<AppTj> noCategorylist;//信息列表
    XListView listView,listView2;//居民列表
    ImageView add;
    List<AppTj> categroylist;
    ImageView cx1,cx2;

    private TextView starttime1,endtime1,starttime2,endtime2,tjdy,tjdy2;
    private CustomDatePicker customDatePicker;
    public MyApplication baseApp;

    public static TjFragment newInstance(MyApplication baseApp) {
        TjFragment newFragment = new TjFragment();
        newFragment.setBaseApp(baseApp);
        return newFragment;
    }

    public MyApplication getBaseApp() {
        return baseApp;
    }

    public void setBaseApp(MyApplication baseApp) {
        this.baseApp = baseApp;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.tj_fragment, null);
        //实例化控件信息
        initView(view);
        //实例化监听
        initListener();
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        pageNum1 = 1;
        getNoCategoryData();
    }

    public void initView(View view) {
        cx1= (ImageView) view.findViewById(R.id.cx1);
        cx2= (ImageView) view.findViewById(R.id.cx2);
        con = getActivity();
        nocategoryLL = (LinearLayout) view.findViewById(R.id.nocategoryLL);
        categoryLL = (LinearLayout) view.findViewById(R.id.categoryLL);
        nocategoryImg = (ImageView) view.findViewById(R.id.nocategoryImg);
        categoryImg = (ImageView) view.findViewById(R.id.categoryImg);
        nocategoryTj = (TextView) view.findViewById(R.id.nocategoryTj);
        categoryTj = (TextView) view.findViewById(R.id.categoryTj);
        listView = (XListView) view.findViewById(R.id.listView);
        listView.setPullLoadEnable(false);

        listView2 = (XListView) view.findViewById(R.id.listView2);
        listView2.setPullLoadEnable(true);
        starttime1 = (TextView) view.findViewById(R.id.starttime1);
        //starttime1.setText(DateConvert.dateToString(DateConvert.getMonthFirstDay(new Date()), DateConvert.YMD));
        starttime1.setText(DateConvert.dateToString(new Date(), DateConvert.YMD));
        endtime1 = (TextView) view.findViewById(R.id.endtime1);
        //endtime1.setText(DateConvert.dateToString(DateConvert.getMonthLastDay(new Date()), DateConvert.YMD));
        endtime1.setText(DateConvert.dateToString(new Date(), DateConvert.YMD));
        starttime2 = (TextView) view.findViewById(R.id.starttime2);
        //starttime2.setText(DateConvert.dateToString(DateConvert.getMonthFirstDay(new Date()), DateConvert.YMD));
        starttime2.setText(DateConvert.dateToString(new Date(), DateConvert.YMD));
        endtime2 = (TextView) view.findViewById(R.id.endtime2);
        //endtime2.setText(DateConvert.dateToString(DateConvert.getMonthLastDay(new Date()), DateConvert.YMD));
        endtime2.setText(DateConvert.dateToString(new Date(), DateConvert.YMD));
        tjdy = (TextView)view.findViewById(R.id.tjdy);
        tjdy2 = (TextView)view.findViewById(R.id.tjdy2);
        getNoCategoryData();
        getCategoryData();
    }

    public void initListener() {

        cx1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNoCategoryData();
            }
        });

        cx2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCategoryData();
            }
        });

        nocategoryTj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nocategoryTj.setTextColor(Color.parseColor("#008B8B"));
                nocategoryImg.setImageResource(R.drawable.tj1);
                nocategoryLL.setVisibility(View.VISIBLE);

                categoryTj.setTextColor(Color.parseColor("#8A8A8A"));
                categoryImg.setImageResource(R.drawable.tj2);
                categoryLL.setVisibility(View.GONE);
                pageNum1 = 1;
                getNoCategoryData();
            }
        });
        categoryTj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                categoryTj.setTextColor(Color.parseColor("#008B8B"));
                categoryImg.setImageResource(R.drawable.tj1);
                categoryLL.setVisibility(View.VISIBLE);

                nocategoryTj.setTextColor(Color.parseColor("#8A8A8A"));
                nocategoryImg.setImageResource(R.drawable.tj2);
                nocategoryLL.setVisibility(View.GONE);
                pageNum1 = 1;
                getCategoryData();
            }
        });

        starttime1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        starttime1.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show( DateConvert.dateToString(DateConvert.getMonthFirstDay(new Date()), DateConvert.YMDHM));
            }
        });

        endtime1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        endtime1.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(now);
            }
        });

        starttime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        starttime2.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show( DateConvert.dateToString(DateConvert.getMonthFirstDay(new Date()), DateConvert.YMDHM));
            }
        });

        endtime2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                customDatePicker = new CustomDatePicker(con, new CustomDatePicker.ResultHandler() {
                    @Override
                    public void handle(String time) { // 回调接口，获得选中的时间
                        endtime2.setText(time.split(" ")[0]);
                    }
                }, "2010-01-01 00:00", now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
                customDatePicker.showSpecificTime(false); // 不显示时和分
                customDatePicker.setIsLoop(false); // 不允许循环滚动
                customDatePicker.show(now);
            }
        });

        tjdy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(baseApp.isAidl()){
                    AidlUtil aidlUtil= AidlUtil.getInstance();
                    aidlUtil.printText(SharedPreferencesUtils.getParam(con,"yljgname","").toString(),36,true, false, 2,1);
                    aidlUtil.printText("对账单",36,true, false, 2,1);
                    aidlUtil.printText("时间："+starttime1.getText().toString()+" ~ "+endtime1.getText().toString(),22,true, false, 1, 1);
                    aidlUtil.printXian(1,0);
                    aidlUtil.printText("收费项目                合计费用",22,true, false, 1, 1);
                    aidlUtil.printXian(2,0);
                    BigDecimal total = new BigDecimal("0");
                    if(null ==noCategorylist || noCategorylist.size()<=0){
                        //aidlUtil.printText("暂无数据", 22, true, false, 1, 1);
                    }else {
                        for (AppTj appTj : noCategorylist) {//"护理费                    25"
                            //aidlUtil.printText(appTj.getYsname()+"                    "+appTj.getTotalfy(), 22, true, false, 1, 1);
                            total = total.add(appTj.getTotalfy());
                        }
                    }

                    if(null ==categroylist || categroylist.size()<=0){
                        aidlUtil.printText("暂无明细", 22, true, false, 1, 1);
                    }else {
                        for (AppTj appTj : categroylist) {//"护理费                    25"
                            aidlUtil.printText(StringUtils.getSpaceStr(appTj.getXmname())+appTj.getTotalfy(), 22, true, false, 1, 1);
                        }
                    }
                    aidlUtil.printXian(1,1);
                    aidlUtil.printText("费用合计："+total+"  ",22,true, false, 1, 1);
                    aidlUtil.printText("打印时间："+DateConvert.dateToString(new Date(), DateConvert.YMDHMS),22,true, false, 1, 1);
                    aidlUtil.printText("收费员："+SharedPreferencesUtils.getParam(con, "uname", "").toString(),22,true, false, 1, 4);
                }else{
                    //BluetoothUtil.sendData(send);
                }
            }
        });

        tjdy2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(baseApp.isAidl()){
                    AidlUtil aidlUtil= AidlUtil.getInstance();
                    aidlUtil.printText(SharedPreferencesUtils.getParam(con,"yljgname","").toString(),36,true, false, 2,1);
                    aidlUtil.printText("对账单",36,true, false, 2,1);
                    aidlUtil.printText("时间："+starttime1.getText().toString()+" ~ "+endtime1.getText().toString(),22,true, false, 1, 1);
                    aidlUtil.printXian(1,0);
                    aidlUtil.printText("收费项目                合计费用",22,true, false, 1, 1);
                    aidlUtil.printXian(2,0);
                    BigDecimal total = new BigDecimal("0");
                    if(null ==noCategorylist || noCategorylist.size()<=0){
                        //aidlUtil.printText("暂无数据", 22, true, false, 1, 1);
                    }else {
                        for (AppTj appTj : noCategorylist) {//"护理费                    25"
                            //aidlUtil.printText(appTj.getYsname()+"                    "+appTj.getTotalfy(), 22, true, false, 1, 1);
                            total = total.add(appTj.getTotalfy());
                        }
                    }

                    if(null ==categroylist || categroylist.size()<=0){
                        aidlUtil.printText("暂无明细", 22, true, false, 1, 1);
                    }else {
                        for (AppTj appTj : categroylist) {//"护理费                    25"
                            aidlUtil.printText(StringUtils.getSpaceStr(appTj.getXmname())+appTj.getTotalfy(), 22, true, false, 1, 1);
                        }
                    }
                    aidlUtil.printXian(1,1);
                    aidlUtil.printText("费用合计："+total+"  ",22,true, false, 1, 1);
                    aidlUtil.printText("打印时间："+DateConvert.dateToString(new Date(), DateConvert.YMDHMS),22,true, false, 1, 1);
                    aidlUtil.printText("收费员："+SharedPreferencesUtils.getParam(con, "uname", "").toString(),22,true, false, 1, 4);
                }else{
                    //BluetoothUtil.sendData(send);
                }
            }
        });
    }

    public void getNoCategoryData() {
        if (!NetWorkUtils.isNetworkConnected(con)) {
            MyToastUtil.ShowToast(con, "网络异常");
        } else {
            RequestParams ps = new RequestParams();
            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps.add("type", "2");
            ps.add("page", pageNum1 + "");
            ps.add("isgly", SharedPreferencesUtils.getParam(con, "isgly", "0").toString());
            if (!StringUtils.isEmpty(starttime1.getText().toString())) {
                ps.add("starttime", starttime1.getText().toString());
            }
            if (!StringUtils.isEmpty(endtime1.getText().toString())) {
                ps.add("endtime", endtime1.getText().toString());
            }

            UserClient.get(HttpUrl.GetTjBySjAll, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFailure(int statusCode, Throwable error, String content) {
                    super.onFailure(statusCode, error, content);
                    MyToastUtil.ShowToast(con, "请求失败");
                }

                @Override
                public void onSuccess(String content) {
                    super.onSuccess(content);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if(ret.getCode().equals("202")){
                        MyToastUtil.ShowToast(con, "超出页码");
                    }else if (ret.getCode().equals("200")) {
                        int totalPage = Integer.parseInt(ret.getTotalPage());
                        if (pageNum1 == 1)
                            noCategorylist = new ArrayList<AppTj>();
                        List<AppTj> ll = JSON.parseArray(ret.getList(), AppTj.class);
                        for (int i = 0; i < ll.size(); i++) {
                            noCategorylist.add(ll.get(i));
                        }
                        listView.setSelection(noCategorylist.size() - ll.size());
                        listView.stopRefresh();
                        listView.stopLoadMore();
                        listView.setRefreshTime("刚刚");
                        listView.setPullLoadEnable(totalPage<=1 ? false : false);
                        listView.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getNoCategoryData();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getNoCategoryData();
                            }
                        });
                        listView.setAdapter(new CommonAdapter<AppTj>(con, noCategorylist, R.layout.tj_item) {
                            @Override
                            public void convert(ViewHolder helper, AppTj item) {
                                helper.setText(R.id.name, item.getYsname());
                                helper.setText(R.id.number, item.getTotalfy()+"    ");
                            }
                        });
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            }
                        });
                    } else {
                        MyToastUtil.ShowToast(con, "获取错误");
                    }
                }
            });
        }
    }

    public void getCategoryData() {
        if (!NetWorkUtils.isNetworkConnected(con)) {
            MyToastUtil.ShowToast(con, "网络异常");
        } else {
            RequestParams ps = new RequestParams();
            ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
            ps.add("type", "2");
            ps.add("page", pageNum1 + "");
            ps.add("isgly", SharedPreferencesUtils.getParam(con, "isgly", "0").toString());
            if (!StringUtils.isEmpty(starttime2.getText().toString())) {
                ps.add("starttime", starttime2.getText().toString());
            }
            if (!StringUtils.isEmpty(endtime2.getText().toString())) {
                ps.add("endtime", endtime2.getText().toString());
            }

            UserClient.get(HttpUrl.GetTjBySjOrderFl, ps, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    super.onStart();
                }

                @Override
                public void onFailure(int statusCode, Throwable error, String content) {
                    super.onFailure(statusCode, error, content);
                    MyToastUtil.ShowToast(con, "请求失败");
                }

                @Override
                public void onSuccess(String content) {
                    super.onSuccess(content);
                    RetMsg ret = JSON.parseObject(content, RetMsg.class);
                    if(ret.getCode().equals("202")){
                        MyToastUtil.ShowToast(con, "超出页码");
                    }else if (ret.getCode().equals("200")) {
                        int totalPage = Integer.parseInt(ret.getTotalPage());
                        if (pageNum1 == 1)
                            categroylist = new ArrayList<AppTj>();
                        List<AppTj> ll = JSON.parseArray(ret.getList(), AppTj.class);
                        for (int i = 0; i < ll.size(); i++) {
                            categroylist.add(ll.get(i));
                        }
                        listView2.setSelection(categroylist.size() - ll.size());
                        listView2.stopRefresh();
                        listView2.stopLoadMore();
                        listView2.setRefreshTime("刚刚");
                        listView2.setPullLoadEnable(totalPage<=1 ? false : true);
                        listView2.setXListViewListener(new XListView.IXListViewListener() {
                            @Override
                            public void onRefresh() {
                                pageNum1 = 1;
                                getCategoryData();
                            }

                            @Override
                            public void onLoadMore() {
                                pageNum1 = pageNum1 + 1;
                                getCategoryData();
                            }
                        });
                        listView2.setAdapter(new CommonAdapter<AppTj>(con, categroylist, R.layout.tj_item) {
                            @Override
                            public void convert(ViewHolder helper, AppTj item) {
                                helper.setText(R.id.name, item.getXmname());
                                helper.setText(R.id.number, item.getTotalfy()+"    ");
                            }
                        });
                        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            }
                        });
                    } else {
                        MyToastUtil.ShowToast(con, "获取错误");
                    }
                }
            });
        }
    }

}
